    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include "bondconfigdialog.h"
    #include "bridgeconfigdialog.h"
    #include "networkcardwidget.h"
    #include "statusmessagewidget.h"
    #include <QListWidgetItem>
    #include <QIcon>
    #include <QFont>
    #include <QResizeEvent>
    #include <QMenu>
    #include <QAction>
    #include <QToolButton>
    #include <QActionGroup>
    #include <QSizePolicy>
    #include <QLabel>
    #include <QMouseEvent>
    #include <QApplication>
    #include <QStyle>
    #include <QPalette>
    #include <QFrame>   // 确保包含了 QFrame 头文件
    #include <QDebug>
    #include <QCoreApplication>
    #include <QTableWidget>
    #include <QHeaderView>
    #include <QTableWidgetItem>
    #include <QMessageBox>
    #include <QProcess>
    #include "networkcontrol.h"
    #include <QTimer>
    #include <QInputDialog>
    #include <QLineEdit>
    #include "networkdiagnosewidget.h"
    #include "networkstatusdialog.h"
    #include <cstdio>
    #include "networkpropertydialog.h"
    #include <QStyledItemDelegate>
    #include "routemanagerdialog.h" // 添加路由管理对话框头文件
    #include <QFileInfo>
    #include <unistd.h>
    #include <QFile>
    #include <QTextStream>
    #include <QProcessEnvironment>
    #include <PolkitQt1/Authority>
    #include <PolkitQt1/Details>
    #include <QEventLoop>
    #include <QElapsedTimer>
    #include <QThread>
    #include "aboutdialog.h"

    struct CardData {
        QString iconPath;
        QString name;
        QString desc;
        QString status;
    };

    // 屏蔽QListWidget选中项竖线的委托
    class NoFocusDelegate : public QStyledItemDelegate {
    public:
        using QStyledItemDelegate::QStyledItemDelegate;
        void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
            QStyleOptionViewItem opt(option);
            opt.state &= ~QStyle::State_HasFocus;
            opt.state &= ~QStyle::State_Selected;
            QStyledItemDelegate::paint(painter, opt, index);
        }
    };

    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
        , m_currentViewMode(NetworkCardWidget::TileMode) // 初始化为平铺模式
        , m_networkInfo(new NetworkInfo(this))
        , m_networkControl(new NetworkControl(this))
    {
        ui->setupUi(this);

        // 设置窗口图标
        setWindowIcon(QIcon(":/icons/resources/logo.png"));

        // 连接NetworkInfo信号
        connect(m_networkInfo, &NetworkInfo::networkInfoUpdated, this, &MainWindow::onNetworkInfoUpdated);
        connect(m_networkInfo, &NetworkInfo::errorOccurred, this, &MainWindow::onNetworkError);

        // 设置状态栏背景色为白色，移除边框，并移除默认填充和边距
        ui->statusbar->setStyleSheet("QStatusBar { background-color: white; border: none; padding: 0px; margin: 0px; } QStatusBar::item { border: none; padding: 0px; margin: 0px; background-color: transparent; }");
        ui->statusbar->setContentsMargins(0,0,0,0); // 确保状态栏自身没有内容边距
        if (ui->statusbar->layout()) {
            if (QBoxLayout *layout = qobject_cast<QBoxLayout*>(ui->statusbar->layout())) {
                layout->setSpacing(0); // 移除状态栏内部项之间的间距
            }
        }

        // 添加状态栏消息控件
        statusMessageWidget = new StatusMessageWidget(this);
        ui->statusbar->addWidget(statusMessageWidget);
        updateStatusBar();

        // 添加右侧布局按钮
        listViewButton = new QToolButton(this);
        listViewButton->setFixedSize(24, 24); // 设置固定大小
        listViewButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation));
        listViewButton->setToolTip("列表视图");
        listViewButton->setStyleSheet("QToolButton { background-color: transparent; border: none; padding: 0px; margin: 0px; } QToolButton:hover { background-color: #e0e0e0; }");
        ui->statusbar->addPermanentWidget(listViewButton);

        tileViewButton = new QToolButton(this);
        tileViewButton->setFixedSize(24, 24); // 设置固定大小
        tileViewButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_DesktopIcon));
        tileViewButton->setToolTip("平铺视图");
        tileViewButton->setStyleSheet("QToolButton { background-color: transparent; border: none; padding: 0px; margin: 0px; } QToolButton:hover { background-color: #e0e0e0; }");
        ui->statusbar->addPermanentWidget(tileViewButton);
        
        // 连接视图切换按钮的点击事件
        connect(listViewButton, &QToolButton::clicked, this, [=](){
            for (QAction *action : ui->toolButtonView->menu()->actions()) {
                if (action->text() == "列表") {
                    action->trigger();
                    break;
                }
            }
        });
        connect(tileViewButton, &QToolButton::clicked, this, [=](){
            for (QAction *action : ui->toolButtonView->menu()->actions()) {
                if (action->text() == "大图标") {
                    action->trigger();
                    break;
                }
            }
        });

        int cardWidth = 320;
        int cardHeight = 110;
        int spacing = 32;
        ui->listWidgetNetwork->setViewMode(QListView::IconMode);
        ui->listWidgetNetwork->setResizeMode(QListView::Adjust);
        ui->listWidgetNetwork->setFlow(QListView::LeftToRight);
        ui->listWidgetNetwork->setSpacing(0);
        ui->listWidgetNetwork->setMovement(QListView::Static);
        ui->listWidgetNetwork->setSelectionMode(QAbstractItemView::ExtendedSelection);
        ui->listWidgetNetwork->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->listWidgetNetwork->setAlternatingRowColors(false);
        ui->listWidgetNetwork->setIconSize(QSize(64, 64));
        ui->listWidgetNetwork->setStyleSheet(
            "QListWidget { border: none; padding: 0px; } "
            "QListWidget::item:selected { background-color: transparent; outline: none; border: none; } "
            "QListWidget::item:focus { outline: none; border: none; } "
            "QListWidget::item:hover { background-color: transparent; }"
        );
        ui->listWidgetNetwork->setContentsMargins(0, 0, 0, 0);
        ui->listWidgetNetwork->setMinimumWidth(cardWidth + 2); // 单卡片宽度+微调
        ui->listWidgetNetwork->setGridSize(QSize(cardWidth + spacing, cardHeight + spacing));
        ui->centralwidget->setMinimumWidth(cardWidth + 2);

        // 工具栏视图切换按钮
        QMenu *viewMenu = new QMenu(this);
        QAction *actionTile = viewMenu->addAction("平铺");
        QAction *actionLargeIcon = viewMenu->addAction("大图标");
        QAction *actionList = viewMenu->addAction("列表");

        actionTile->setCheckable(true);
        actionLargeIcon->setCheckable(true);
        actionList->setCheckable(true);

        actionTile->setChecked(true);

        QActionGroup *viewGroup = new QActionGroup(this);
        viewGroup->addAction(actionTile);
        viewGroup->addAction(actionLargeIcon);
        viewGroup->addAction(actionList);
        viewGroup->setExclusive(true);

        // 设置视图按钮的属性和行为
        ui->toolButtonView->setMenu(viewMenu);

        // 初始化 tableWidgetNetwork
        tableWidgetNetwork = new QTableWidget(this);
        tableWidgetNetwork->setColumnCount(6);
        QStringList headers;
        headers << "名称" << "状态" << "设备名" << "连接名称" << "连接性" << "网络类别";
        tableWidgetNetwork->setHorizontalHeaderLabels(headers);
        tableWidgetNetwork->setColumnHidden(3, true); // 隐藏"连接名称"列
        tableWidgetNetwork->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        tableWidgetNetwork->verticalHeader()->setVisible(false);
        tableWidgetNetwork->setSelectionBehavior(QAbstractItemView::SelectRows);
        tableWidgetNetwork->setSelectionMode(QAbstractItemView::ExtendedSelection);
        tableWidgetNetwork->setEditTriggers(QAbstractItemView::NoEditTriggers);
        tableWidgetNetwork->setShowGrid(false); // 关闭表格线
        tableWidgetNetwork->setAlternatingRowColors(false);
        tableWidgetNetwork->setFrameShape(QFrame::NoFrame);
        tableWidgetNetwork->setStyleSheet(
            "QTableWidget { border: none; background: white; selection-background-color: #e5e5e5; selection-color: black; } "
            "QTableWidget::item:selected { background: #e5e5e5; color: black; border: none; } "
            "QTableWidget::item { border: none; } "
            "QHeaderView::section { background: #f5f5f5; font-weight: bold; border: none; } "
        );
        tableWidgetNetwork->setIconSize(QSize(20, 20)); // 保证小图标显示
        tableWidgetNetwork->setVisible(false);
        ui->verticalLayout->addWidget(tableWidgetNetwork);

        // 监听表格选中变化，调用与卡片一致的槽
        connect(tableWidgetNetwork, &QTableWidget::itemSelectionChanged, this, &MainWindow::onNetworkSelectionChanged);
        // 监听表格右键菜单
        tableWidgetNetwork->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(tableWidgetNetwork, &QTableWidget::customContextMenuRequested, this, &MainWindow::onNetworkContextMenuRequested);

        // 安装事件过滤器，空白处点击清除选中
        tableWidgetNetwork->viewport()->installEventFilter(this);

        // 视图切换逻辑
        connect(actionTile, &QAction::triggered, this, [=]() {
            m_currentViewMode = NetworkCardWidget::TileMode; // 更新当前视图模式
            
            // 记录当前选中状态
            QSet<QString> selectedDevs;
            for (QListWidgetItem *item : ui->listWidgetNetwork->selectedItems()) {
                selectedDevs.insert(item->data(Qt::UserRole).toString());
            }
            
            int cardWidth = 320;
            int cardHeight = 110;
            int spacing = 32;
            ui->listWidgetNetwork->setViewMode(QListView::IconMode);
            ui->listWidgetNetwork->setIconSize(QSize(48, 48));
            ui->listWidgetNetwork->setGridSize(QSize(cardWidth + spacing, cardHeight + spacing));
            ui->listWidgetNetwork->setFlow(QListView::LeftToRight);
            ui->listWidgetNetwork->setResizeMode(QListView::Adjust);

            for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
                QListWidgetItem *item = ui->listWidgetNetwork->item(i);
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    cardWidget->setViewMode(NetworkCardWidget::TileMode);
                    cardWidget->updateGeometry();
                    item->setSizeHint(cardWidget->sizeHint());
                }
            }
            ui->listWidgetNetwork->setVisible(true);
            if (tableWidgetNetwork) tableWidgetNetwork->setVisible(false);
            ui->listWidgetNetwork->update();
            QCoreApplication::processEvents();
            
            // 恢复选中状态
            for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
                QListWidgetItem *item = ui->listWidgetNetwork->item(i);
                QString devName = item->data(Qt::UserRole).toString();
                item->setSelected(selectedDevs.contains(devName));
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    cardWidget->setSelected(selectedDevs.contains(devName));
                }
            }
        });
        connect(actionLargeIcon, &QAction::triggered, this, [=]() {
            m_currentViewMode = NetworkCardWidget::LargeIconMode; // 更新当前视图模式
            // 记录当前选中状态
            QSet<QString> selectedDevs;
            for (QListWidgetItem *item : ui->listWidgetNetwork->selectedItems()) {
                selectedDevs.insert(item->data(Qt::UserRole).toString());
            }
            ui->listWidgetNetwork->setViewMode(QListView::IconMode);
            ui->listWidgetNetwork->setIconSize(QSize(64, 64));
            int cardWidth = 330;
            int cardHeight = 240; // 必须和NetworkCardWidget::sizeHint一致
            int spacing = 32;
            ui->listWidgetNetwork->setGridSize(QSize(cardWidth + spacing, cardHeight + spacing));
            for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
                QListWidgetItem *item = ui->listWidgetNetwork->item(i);
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    cardWidget->setViewMode(NetworkCardWidget::LargeIconMode);
                    cardWidget->updateGeometry();
                    item->setSizeHint(cardWidget->sizeHint());
                }
            }
            ui->listWidgetNetwork->setVisible(true);
            if (tableWidgetNetwork) tableWidgetNetwork->setVisible(false);
            ui->listWidgetNetwork->update();
            QCoreApplication::processEvents();
            // 恢复选中状态
            for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
                QListWidgetItem *item = ui->listWidgetNetwork->item(i);
                QString devName = item->data(Qt::UserRole).toString();
                item->setSelected(selectedDevs.contains(devName));
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    cardWidget->setSelected(selectedDevs.contains(devName));
                }
            }
        });
        connect(actionList, &QAction::triggered, this, [=]() {
            m_currentViewMode = NetworkCardWidget::TileMode;
            ui->listWidgetNetwork->setVisible(false);
            if (tableWidgetNetwork) {
                tableWidgetNetwork->setVisible(true);
                // 设置选择模式
                tableWidgetNetwork->setSelectionBehavior(QAbstractItemView::SelectRows);
                tableWidgetNetwork->setSelectionMode(QAbstractItemView::ExtendedSelection);
            // 填充表格数据
                updateTableView();
            }
        });

        // 加载真实的网络连接数据
        loadNetworkConnections();

        connect(ui->listWidgetNetwork, &QListWidget::itemSelectionChanged, this, &MainWindow::onNetworkSelectionChanged);
        ui->listWidgetNetwork->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(ui->listWidgetNetwork, &QListWidget::customContextMenuRequested, this, &MainWindow::onNetworkContextMenuRequested);

        if (ui->listWidgetNetwork->count() > 0) {
            ui->listWidgetNetwork->setCurrentRow(0);
            auto *w = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(ui->listWidgetNetwork->item(0)));
            if (w) w->setSelected(true);
        }

        // 确保初始时就触发一次 resizeEvent 来设置正确的布局和 gridSize
        QResizeEvent initialResizeEvent(size(), size());
        QCoreApplication::sendEvent(this, &initialResizeEvent);

        // --- 强制刷新所有卡片布局，防止首次显示错乱 ---
        for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
            QListWidgetItem *item = ui->listWidgetNetwork->item(i);
            NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
            if (cardWidget) {
                cardWidget->setViewMode(m_currentViewMode);
                cardWidget->updateGeometry();
                cardWidget->update();
            }
        }
        QCoreApplication::processEvents();

        ui->actionDisable->setVisible(false);
        ui->actionDiagnose->setVisible(false);
        ui->actionRename->setVisible(false);
        ui->actionStatus->setVisible(false);
        ui->actionSetting->setVisible(false);

        connect(ui->actionDiagnose, &QAction::triggered, this, &MainWindow::onDiagnoseNetwork);
        connect(ui->actionRename, &QAction::triggered, this, &MainWindow::onRenameNetwork);
        connect(ui->actionStatus, &QAction::triggered, this, &MainWindow::showNetworkStatusDialog);
        connect(ui->listWidgetNetwork, &QListWidget::itemDoubleClicked, this, [=](QListWidgetItem*){ showNetworkStatusDialog(); });
        if (tableWidgetNetwork) {
            connect(tableWidgetNetwork, &QTableWidget::itemDoubleClicked, this, [=](QTableWidgetItem*){ showNetworkStatusDialog(); });
        }

        // 主动刷新一次，避免首次无数据
        if (m_networkInfo) m_networkInfo->refreshAll();

        // 在构造函数中添加连接
        connect(ui->actionSetting, &QAction::triggered, this, &MainWindow::onSettingNetwork);

        // 为listWidgetNetwork设置委托
        ui->listWidgetNetwork->setItemDelegate(new NoFocusDelegate(ui->listWidgetNetwork));

        aboutAct = new QAction("关于", this);
        connect(aboutAct, &QAction::triggered, this, &MainWindow::showAboutDialog);
        // 视图菜单添加
        ui->toolButtonView->menu()->addAction(aboutAct);
    }

    void MainWindow::resizeEvent(QResizeEvent *event) {
        QMainWindow::resizeEvent(event);
        int w = ui->listWidgetNetwork->width();
        int currentCardWidth = 0;
        int currentCardHeight = 0;
        int currentSpacing = 32;
        if (m_currentViewMode == NetworkCardWidget::TileMode) {
            currentCardWidth = 320;
            currentCardHeight = 110;
            currentSpacing = 32;
            ui->listWidgetNetwork->setFlow(QListView::LeftToRight);
            ui->listWidgetNetwork->setResizeMode(QListView::Adjust);
        } else if (m_currentViewMode == NetworkCardWidget::LargeIconMode) {
            currentCardWidth = 330;
            currentCardHeight = 240; // 必须和NetworkCardWidget::sizeHint一致
            currentSpacing = 32;
            ui->listWidgetNetwork->setFlow(QListView::LeftToRight);
            ui->listWidgetNetwork->setResizeMode(QListView::Adjust);
        } else if (ui->listWidgetNetwork->viewMode() == QListView::ListMode) {
            ui->listWidgetNetwork->setGridSize(QSize());
            ui->listWidgetNetwork->setFlow(QListView::TopToBottom);
            ui->listWidgetNetwork->setResizeMode(QListView::Fixed);
            for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
                QListWidgetItem *item = ui->listWidgetNetwork->item(i);
                item->setSizeHint(QSize(w, 48));
            }
            return;
        }
        int countPerRow = qMax(1, (w) / (currentCardWidth + currentSpacing));
        int gridWidth = currentCardWidth + (countPerRow > 1 ? currentSpacing : 0);
        int gridHeight = currentCardHeight + currentSpacing;
        ui->listWidgetNetwork->setGridSize(QSize(gridWidth, gridHeight));
    }

    bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
        if (obj == tableWidgetNetwork->viewport() && tableWidgetNetwork->isVisible()) {
            if (event->type() == QEvent::MouseButtonPress) {
                QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
                QModelIndex idx = tableWidgetNetwork->indexAt(mouseEvent->pos());
                if (!idx.isValid()) {
                    tableWidgetNetwork->clearSelection();
                    onNetworkSelectionChanged();
                }
            }
        }
        return QMainWindow::eventFilter(obj, event);
    }

    QList<ConnectionInfo> MainWindow::findProfiles(const QString &devName, const QString &connName) {
        QList<ConnectionInfo> result;
        for (const auto &conn : m_networkInfo->getAllConnections()) {
            if (conn.device == devName || (!connName.isEmpty() && conn.name == connName)) result << conn;
        }
        return result;
    }

    void MainWindow::onNetworkSelectionChanged() {
        bool anySelected = false;
        int selectedCount = 0;
        QString devName, connName, statusText;
        DeviceType devType = DeviceType::Unknown;
        QList<ConnectionInfo> profiles;
        ConnectionInfo activeProfile;
        if (ui->listWidgetNetwork->isVisible()) {
            anySelected = !ui->listWidgetNetwork->selectedItems().isEmpty();
            selectedCount = ui->listWidgetNetwork->selectedItems().count();
            for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
                QListWidgetItem *item = ui->listWidgetNetwork->item(i);
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    cardWidget->setSelected(item->isSelected());
                }
            }
            // 获取当前选中项信息（用selectedItems().first()替代currentItem）
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            QListWidgetItem* item = selected.isEmpty() ? nullptr : selected.first();
            if (item) {
                devName = item->data(Qt::UserRole).toString();
                connName = item->data(Qt::UserRole+1).toString();
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    statusText = cardWidget->findChild<QLabel*>("statusLabel")->text();
                }
            }
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            anySelected = !tableWidgetNetwork->selectedItems().isEmpty();
            selectedCount = tableWidgetNetwork->selectionModel()->selectedRows().count();
            // 获取当前选中项信息
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            if (!sel.isEmpty()) {
                int row = sel.first().row();
                devName = tableWidgetNetwork->item(row, 2) ? tableWidgetNetwork->item(row, 2)->text() : "";
                connName = tableWidgetNetwork->item(row, 0) ? tableWidgetNetwork->item(row, 0)->text() : "";
                statusText = tableWidgetNetwork->item(row, 1) ? tableWidgetNetwork->item(row, 1)->text() : "";
            }
        }
        // 查找设备类型
        if (!devName.isEmpty()) {
            for (const auto &dev : m_networkInfo->getAllDevices()) {
                if (dev.name == devName) { devType = dev.type; break; }
            }
            profiles = findProfiles(devName, connName);
            for (const auto &conn : profiles) {
                if (conn.device == devName) { activeProfile = conn; break; }
            }
        }
        // 动态设置工具栏第一个按钮
        ui->actionDisable->setEnabled(anySelected);
        ui->actionDisable->setVisible(anySelected);
        disconnect(ui->actionDisable, nullptr, this, nullptr); // 断开所有旧连接
        
        // 检查是否为bond-slave-*或bridge-slave-*连接，如果是则禁用管理操作
        bool isBondSlave = false;
        bool isBridgeSlave = false;
        if (!devName.isEmpty()) {
            for (const auto &conn : m_networkInfo->getAllConnections()) {
                if (conn.device == devName && conn.name.startsWith("bond-slave-")) {
                    isBondSlave = true;
                }
                if (conn.device == devName && conn.name.startsWith("bridge-slave-")) {
                    isBridgeSlave = true;
                }
            }
        }
        
        if (!anySelected) {
            ui->actionDisable->setText("禁用此网络设备");
        } else if (isBondSlave || isBridgeSlave) {
            // bond-slave-*或bridge-slave-*连接：禁用所有管理操作
            ui->actionDisable->setText("从属网卡（不可管理）");
            ui->actionDisable->setEnabled(false);
        } else if (profiles.isEmpty()) {
            ui->actionDisable->setText("新建连接");
            connect(ui->actionDisable, &QAction::triggered, this, &MainWindow::onAddConnection);
        } else if (!activeProfile.name.isEmpty() && activeProfile.status == ConnectionStatus::Connected) {
            ui->actionDisable->setText("禁用此网络设备");
            connect(ui->actionDisable, &QAction::triggered, this, &MainWindow::onDisableNetwork);
        } else {
            ui->actionDisable->setText("启用此网络设备");
            connect(ui->actionDisable, &QAction::triggered, this, &MainWindow::onEnableNetwork);
        }
        
        // 为bond-slave-*或bridge-slave-*连接禁用状态和属性按钮
        ui->actionDiagnose->setVisible(anySelected);
        ui->actionDiagnose->setEnabled(anySelected && statusText == "已连接" && !isBondSlave && !isBridgeSlave);
        ui->actionRename->setVisible(anySelected);
        ui->actionRename->setEnabled(anySelected && !isBondSlave && !isBridgeSlave);
        ui->actionStatus->setVisible(anySelected);
        ui->actionStatus->setEnabled(anySelected && statusText == "已连接" && !isBondSlave && !isBridgeSlave);
        ui->actionSetting->setVisible(anySelected);
        ui->actionSetting->setEnabled(anySelected && !isBondSlave && !isBridgeSlave);
        updateStatusBar(selectedCount);
    }

    // 能力判断函数（UI层初步实现）
    bool MainWindow::canBondUI(const QList<ConnectionInfo>& conns) {
        if (conns.size() < 2) return false;
        QSet<QString> devs, macs;
        
        // 获取当前已绑定的网卡、桥接从属网卡和虚拟接口
        QSet<QString> bondedDevices, bridgedDevices, virtualInterfaces;
        for (const auto& conn : m_networkInfo->getAllConnections()) {
            // 检查是否是绑定从属网卡（通过连接名称判断）
            if (conn.name.contains("bond-slave-")) {
                bondedDevices.insert(conn.device);
            }
            // 检查是否是桥接从属网卡（通过连接名称判断）
            if (conn.name.contains("bridge-slave-")) {
                bridgedDevices.insert(conn.device);
            }
            // 检查是否是虚拟绑定接口
            if (conn.type == DeviceType::Bond || conn.name.startsWith("bond")) {
                virtualInterfaces.insert(conn.device);
            }
            // 检查是否是桥接接口
            if (conn.type == DeviceType::Bridge || conn.device.startsWith("br")) {
                virtualInterfaces.insert(conn.device);
            }
        }
        
        for (const auto& c : conns) {
            // 检查是否是虚拟接口
            if (virtualInterfaces.contains(c.device)) {
                return false; // 虚拟接口不能参与绑定
            }
            // 检查是否已经是绑定从属网卡
            if (bondedDevices.contains(c.device)) {
                return false; // 已绑定的网卡不能再次参与绑定
            }
            // 检查是否已经是桥接从属网卡
            if (bridgedDevices.contains(c.device)) {
                return false; // 已桥接的网卡不能参与绑定
            }
            if (c.type != DeviceType::Ethernet) return false;
            if (devs.contains(c.device)) return false;
            devs.insert(c.device);
            if (c.macAddress.isEmpty()) return false;
            if (macs.contains(c.macAddress)) return false;
            macs.insert(c.macAddress);
            // driver字段仅作提示，不做强制判断
        }
        return true;
    }
    bool MainWindow::canBridgeUI(const QList<ConnectionInfo>& conns) {
        if (conns.size() < 2) return false;
        
        // 获取当前已绑定的网卡、桥接从属网卡和虚拟接口
        QSet<QString> bondedDevices, bridgedDevices, virtualInterfaces;
        for (const auto& conn : m_networkInfo->getAllConnections()) {
            // 检查是否是绑定从属网卡（通过连接名称判断）
            if (conn.name.contains("bond-slave-")) {
                bondedDevices.insert(conn.device);
            }
            // 检查是否是桥接从属网卡（通过连接名称判断）
            if (conn.name.contains("bridge-slave-")) {
                bridgedDevices.insert(conn.device);
            }
            // 检查是否是虚拟绑定接口
            if (conn.type == DeviceType::Bond || conn.name.startsWith("bond")) {
                virtualInterfaces.insert(conn.device);
            }
            // 检查是否是桥接接口
            if (conn.type == DeviceType::Bridge || conn.device.startsWith("br")) {
                virtualInterfaces.insert(conn.device);
            }
        }
        
        QString baseNet;
        for (const auto& c : conns) {
            // 检查是否是虚拟接口
            if (virtualInterfaces.contains(c.device)) {
                return false; // 虚拟接口不能参与桥接
            }
            // 检查是否已经是绑定从属网卡
            if (bondedDevices.contains(c.device)) {
                return false; // 已绑定的网卡不能参与桥接
            }
            // 检查是否已经是桥接从属网卡
            if (bridgedDevices.contains(c.device)) {
                return false; // 已桥接的网卡不能再次参与桥接
            }
            if (c.type != DeviceType::Ethernet) return false;
            // driver字段仅作提示，不做强制判断
            if (!c.ipAddress.isEmpty() && !c.netmask.isEmpty()) {
                QString net = getNetworkSegment(c.ipAddress, c.netmask);
                if (baseNet.isEmpty()) baseNet = net;
                else if (net != baseNet) return false;
            }
        }
        return true;
    }
    // 辅助函数：获取网络段
    QString MainWindow::getNetworkSegment(const QString& ip, const QString& mask) {
        QStringList ipParts = ip.split('.');
        QStringList maskParts = mask.split('.');
        if (ipParts.size() != 4 || maskParts.size() != 4) return "";
        QStringList netParts;
        for (int i = 0; i < 4; ++i) {
            bool ok1, ok2;
            int ipVal = ipParts[i].toInt(&ok1);
            int maskVal = maskParts[i].toInt(&ok2);
            if (!ok1 || !ok2) return "";
            netParts << QString::number(ipVal & maskVal);
        }
        return netParts.join('.');
    }

    void MainWindow::onNetworkContextMenuRequested(const QPoint &pos) {
        QMenu menu;
        QString devName, connName, statusText;
        DeviceType devType = DeviceType::Unknown;
        bool isEnabled = false;
        QList<ConnectionInfo> profiles;
        ConnectionInfo activeProfile;
        QList<ConnectionInfo> selectedConns;
        QSet<QString> selectedDevs;
        // 动态添加绑定/桥接菜单项
        if (ui->listWidgetNetwork->isVisible()) {
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            for (auto* item : selected) {
                QString devName = item->data(Qt::UserRole).toString();
                if (!selectedDevs.contains(devName)) {
                    selectedDevs.insert(devName);
                    bool found = false;
                    for (const auto& conn : m_networkInfo->getAllConnections()) {
                        if (conn.device == devName && conn.type == DeviceType::Ethernet) {
                            // 检查并补充MAC地址
                            ConnectionInfo connCopy = conn;
                            if (connCopy.macAddress.isEmpty()) {
                                for (const auto &dev : m_networkInfo->getAllDevices()) {
                                    if (dev.name == devName) {
                                        connCopy.macAddress = dev.macAddress;
                                        break;
                                    }
                                }
                            }
                            selectedConns << connCopy;
                            found = true;
                            break;
                        }
                    }
                    // 填充selectedConns时，不管连接状态，只要是物理网卡都补全macAddress
                    if (!found) {
                        ConnectionInfo dummy;
                        dummy.device = devName;
                        dummy.type = DeviceType::Ethernet;
                        // 补充macAddress字段
                        for (const auto &dev : m_networkInfo->getAllDevices()) {
                            if (dev.name == devName) {
                                dummy.macAddress = dev.macAddress;
                                break;
                            }
                        }
                        selectedConns << dummy;
                    }
                }
            }
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            for (const auto& idx : sel) {
                int row = idx.row();
                QString devName = tableWidgetNetwork->item(row, 2) ? tableWidgetNetwork->item(row, 2)->text() : "";
                if (!selectedDevs.contains(devName)) {
                    selectedDevs.insert(devName);
                    bool found = false;
                    for (const auto& conn : m_networkInfo->getAllConnections()) {
                        if (conn.device == devName && conn.type == DeviceType::Ethernet) {
                            // 检查并补充MAC地址
                            ConnectionInfo connCopy = conn;
                            if (connCopy.macAddress.isEmpty()) {
                                for (const auto &dev : m_networkInfo->getAllDevices()) {
                                    if (dev.name == devName) {
                                        connCopy.macAddress = dev.macAddress;
                                        break;
                                    }
                                }
                            }
                            selectedConns << connCopy;
                            found = true;
                            break;
                        }
                    }
                    // 填充selectedConns时，不管连接状态，只要是物理网卡都补全macAddress
                    if (!found) {
                        ConnectionInfo dummy;
                        dummy.device = devName;
                        dummy.type = DeviceType::Ethernet;
                        // 补充macAddress字段
                        for (const auto &dev : m_networkInfo->getAllDevices()) {
                            if (dev.name == devName) {
                                dummy.macAddress = dev.macAddress;
                                break;
                            }
                        }
                        selectedConns << dummy;
                    }
                }
            }
        }
        // 记录右键菜单操作的item
        m_contextMenuListItem = nullptr;
        m_contextMenuTableRow = -1;
        m_contextMenuProfileName.clear();

        if (ui->listWidgetNetwork->isVisible()) {
            QListWidgetItem *item = ui->listWidgetNetwork->itemAt(pos);
            if (item) {
                m_contextMenuListItem = item;
                // desc就是当前卡片显示的profile名
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    QLabel* descLabel = cardWidget->findChild<QLabel*>("descLabel");
                    if (descLabel) m_contextMenuProfileName = descLabel->text();
                    statusText = cardWidget->findChild<QLabel*>("statusLabel")->text();
                }
                devName = item->data(Qt::UserRole).toString();
                connName = item->data(Qt::UserRole+1).toString();
            }
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            QModelIndex index = tableWidgetNetwork->indexAt(pos);
            if (index.isValid()) {
                m_contextMenuTableRow = index.row();
                // 关键：记录"连接名"列（第3列，实际如有不同请调整）
                if (tableWidgetNetwork->columnCount() > 3 && tableWidgetNetwork->item(index.row(), 3)) {
                    m_contextMenuProfileName = tableWidgetNetwork->item(index.row(), 3)->text();
                    connName = tableWidgetNetwork->item(index.row(), 3)->text();
                } else {
                    m_contextMenuProfileName = tableWidgetNetwork->item(index.row(), 0)->text(); // 兜底
                    connName = tableWidgetNetwork->item(index.row(), 0)->text();
                }
                devName = tableWidgetNetwork->item(index.row(), 2)->text();
                statusText = tableWidgetNetwork->item(index.row(), 1)->text();
            }
        }

        if (!devName.isEmpty()) {
            // 查找设备类型和启用状态
                for (const auto &dev : m_networkInfo->getAllDevices()) {
                if (dev.name == devName) {
                    devType = dev.type;
                    isEnabled = dev.isEnabled;
                    break;
                }
            }
            profiles = findProfiles(devName, connName);
            for (const auto &conn : profiles) {
                if (conn.device == devName) { activeProfile = conn; break; }
                }
                if (devType == DeviceType::Loopback) {
                    return;
                }
                
            // 检查是否为bond-slave-*连接
            bool isBondSlave = false;
            bool isBridgeSlave = false;
            for (const auto &conn : profiles) {
                if (conn.name.startsWith("bond-slave-")) {
                    isBondSlave = true;
                }
                if (conn.name.startsWith("bridge-slave-")) {
                    isBridgeSlave = true;
                }
            }
            
            // 检查是否为bond接口
            bool isBondInterface = false;
            if (devType == DeviceType::Bond || (activeProfile.name.startsWith("bond") && !activeProfile.name.startsWith("bond-slave-"))) {
                isBondInterface = true;
            }
            
            // 检查是否为bridge接口
            bool isBridgeInterface = false;
            if (devType == DeviceType::Bridge || (activeProfile.name.startsWith("br") && !activeProfile.name.startsWith("bridge-slave-"))) {
                isBridgeInterface = true;
            }
                
            if (profiles.isEmpty()) {
                menu.addAction("新建连接", this, &MainWindow::onAddConnection);
                        } else {
                // 有profile，判断当前状态
                if (!activeProfile.name.isEmpty() && activeProfile.status == ConnectionStatus::Connected) {
                    if (isBondSlave || isBridgeSlave) {
                        menu.addAction("从属网卡（不可管理）")->setEnabled(false);
                    } else if (isBondInterface) {
                    menu.addAction("禁用", this, &MainWindow::onDisableNetwork);
                        menu.addSeparator();
                        QAction* editBondAct = menu.addAction("编辑绑定成员...");
                        connect(editBondAct, &QAction::triggered, this, [this, activeProfile]() {
                            onEditBondMembers(activeProfile);
                        });
                        QAction* unbondAct = menu.addAction("解除绑定");
                        connect(unbondAct, &QAction::triggered, this, [this, activeProfile]() {
                            onUnbondNetwork(activeProfile);
                        });
                    } else if (isBridgeInterface) {
                        menu.addAction("禁用", this, &MainWindow::onDisableNetwork);
                        menu.addSeparator();
                        QAction* editBridgeAct = menu.addAction("编辑桥接成员...");
                        connect(editBridgeAct, &QAction::triggered, this, [this, activeProfile]() {
                            onEditBridgeMembers(activeProfile);
                        });
                        QAction* unbridgeAct = menu.addAction("解除桥接");
                        connect(unbridgeAct, &QAction::triggered, this, [this, activeProfile]() {
                            onUnbridgeNetwork(activeProfile);
                        });
                    } else {
                        menu.addAction("禁用", this, &MainWindow::onDisableNetwork);
                    }
                } else {
                    if (isBondSlave || isBridgeSlave) {
                        menu.addAction("从属网卡（不可管理）")->setEnabled(false);
                    } else if (isBondInterface) {
                        menu.addAction("启用", this, &MainWindow::onEnableNetwork);
                        menu.addSeparator();
                        QAction* editBondAct = menu.addAction("编辑绑定成员...");
                        connect(editBondAct, &QAction::triggered, this, [this, activeProfile]() {
                            onEditBondMembers(activeProfile);
                        });
                        QAction* unbondAct = menu.addAction("解除绑定");
                        connect(unbondAct, &QAction::triggered, this, [this, activeProfile]() {
                            onUnbondNetwork(activeProfile);
                        });
                    } else if (isBridgeInterface) {
                        menu.addAction("启用", this, &MainWindow::onEnableNetwork);
                        menu.addSeparator();
                        QAction* editBridgeAct = menu.addAction("编辑桥接成员...");
                        connect(editBridgeAct, &QAction::triggered, this, [this, activeProfile]() {
                            onEditBridgeMembers(activeProfile);
                        });
                        QAction* unbridgeAct = menu.addAction("解除桥接");
                        connect(unbridgeAct, &QAction::triggered, this, [this, activeProfile]() {
                            onUnbridgeNetwork(activeProfile);
                        });
                } else {
                    menu.addAction("启用", this, &MainWindow::onEnableNetwork);
                    }
                }
                    menu.addSeparator();
                    QAction* statusAct = menu.addAction("状态", this, &MainWindow::onStatusNetwork);
                    if (statusText != "已连接" || isBondSlave || isBridgeSlave) statusAct->setEnabled(false);
                    QListWidgetItem* item = ui->listWidgetNetwork->itemAt(pos);
                    if (item && !isBondSlave && !isBridgeSlave) {
                        QAction *actionProperty = new QAction("属性(&R)...", this);
                        connect(actionProperty, &QAction::triggered, this, [this, item](){
                            QString devName = item->data(Qt::UserRole).toString();
                            QString connName = item->data(Qt::UserRole+1).toString();
                            ConnectionInfo connInfo;
                            DeviceInfo devInfo;
                            for (const auto &conn : m_connections) {
                                if (conn.device == devName && conn.name == connName) { connInfo = conn; break; }
                            }
                            if (m_networkInfo) {
                                for (const auto &dev : m_networkInfo->getAllDevices()) {
                                    if (dev.name == devName) { devInfo = dev; break; }
                                }
                            }
                            NetworkPropertyDialog *dlg = new NetworkPropertyDialog(connInfo, devInfo, this);
                            dlg->exec();
                            delete dlg;
                        });
                        menu.addAction(actionProperty);
                    } else if (isBondSlave || isBridgeSlave) {
                        menu.addAction("属性（从属网卡不可设置）")->setEnabled(false);
                    }
                    menu.addSeparator();
                    if (isBondSlave || isBridgeSlave) {
                        menu.addAction("重命名（从属网卡不可重命名）")->setEnabled(false);
                    } else {
                    menu.addAction("重命名", this, &MainWindow::onRenameNetwork);
                    }
                }
            } else {
                menu.addAction("刷新", this, &MainWindow::onRefreshView);
                QMenu *viewSubMenu = menu.addMenu("查看");
                viewSubMenu->addAction(ui->toolButtonView->menu()->actions().at(0));
                viewSubMenu->addAction(ui->toolButtonView->menu()->actions().at(1));
                viewSubMenu->addAction(ui->toolButtonView->menu()->actions().at(2));
            }
        QAction *actionRouteManager = new QAction("路由管理", this);
        connect(actionRouteManager, &QAction::triggered, this, [this]{
            // 路由管理菜单点击槽函数：
            RouteManagerDialog dlg(this);
            dlg.exec();
        });
        menu.addSeparator();
        menu.addAction(actionRouteManager);
        // 动态添加绑定/桥接菜单项
        if (canBondUI(selectedConns)) {
            QAction* bondAct = menu.addAction("绑定这些网卡");
            connect(bondAct, &QAction::triggered, this, [this, selectedConns]() {
                onBondNetworks(selectedConns);
            });
        }
        if (canBridgeUI(selectedConns)) {
            QAction* bridgeAct = menu.addAction("桥接这些网卡");
            connect(bridgeAct, &QAction::triggered, this, [this, selectedConns]() {
                onBridgeNetworks(selectedConns);
            });
        }
        menu.addAction(aboutAct);
        
        if (ui->listWidgetNetwork->isVisible()) {
            menu.exec(ui->listWidgetNetwork->mapToGlobal(pos));
        } else if (tableWidgetNetwork) {
            menu.exec(tableWidgetNetwork->viewport()->mapToGlobal(pos));
        }
    }

    void MainWindow::onDisableNetwork() {
        QString devName;
        if (ui->listWidgetNetwork->isVisible()) {
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            QListWidgetItem* item = selected.isEmpty() ? nullptr : selected.first();
            if (!item) return;
            devName = item->data(Qt::UserRole).toString();
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            if (sel.isEmpty()) return;
            devName = tableWidgetNetwork->item(sel.first().row(), 2)->text();
        }
        QString err;
        if (m_networkControl->disableDevice(devName, &err)) {
            QTimer::singleShot(500, m_networkInfo, &NetworkInfo::refreshAll);
        } else {
            QMessageBox::critical(this, "禁用失败", err);
        }
    }

    void MainWindow::onEnableNetwork() {
        QString devName;
        if (ui->listWidgetNetwork->isVisible()) {
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            QListWidgetItem* item = selected.isEmpty() ? nullptr : selected.first();
            if (!item) return;
            devName = item->data(Qt::UserRole).toString();
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            if (sel.isEmpty()) return;
            devName = tableWidgetNetwork->item(sel.first().row(), 2)->text();
        }
        QString err;
        if (m_networkControl->enableDevice(devName, &err)) {
            QTimer::singleShot(500, m_networkInfo, &NetworkInfo::refreshAll);
        } else {
            QMessageBox::critical(this, "启用失败", err);
        }
    }

    void MainWindow::onDiagnoseNetwork() {
        QString devName, connName;
        ConnectionInfo connInfo;
        DeviceInfo devInfo;
        if (ui->listWidgetNetwork->isVisible()) {
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            QListWidgetItem* item = selected.isEmpty() ? nullptr : selected.first();
            if (!item) return;
            devName = item->data(Qt::UserRole).toString();
            connName = item->data(Qt::UserRole+1).toString();
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            if (sel.isEmpty()) return;
            int row = sel.first().row();
            devName = tableWidgetNetwork->item(row, 2) ? tableWidgetNetwork->item(row, 2)->text() : "";
            connName = tableWidgetNetwork->item(row, 0) ? tableWidgetNetwork->item(row, 0)->text() : "";
        }
        // 查找完整的ConnectionInfo
        for (const auto &conn : m_connections) {
            if (conn.device == devName && conn.name == connName) {
                connInfo = conn;
                break;
            }
        }
        // 查找DeviceInfo
        if (m_networkInfo) {
            for (const auto &dev : m_networkInfo->getAllDevices()) {
                if (dev.name == devName) {
                    devInfo = dev;
                    break;
                }
            }
        }
        NetworkDiagnoseWidget *diag = new NetworkDiagnoseWidget(connInfo, devInfo, this);
        diag->setAttribute(Qt::WA_DeleteOnClose);
        diag->exec();
    }

    void MainWindow::onRenameNetwork() {
        QString connName;
        // 优先使用右键菜单记录的profile名
        if (ui->listWidgetNetwork->isVisible()) {
            if (!m_contextMenuProfileName.isEmpty()) {
                connName = m_contextMenuProfileName;
            } else {
                // 兼容工具栏按钮，退回到当前选中项
                QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
                QListWidgetItem* item = selected.isEmpty() ? nullptr : selected.first();
                if (!item) return;
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (!cardWidget) return;
                QLabel* descLabel = cardWidget->findChild<QLabel*>("descLabel");
                if (!descLabel) return;
                connName = descLabel->text();
            }
            if (connName.isEmpty()) return; // 没有连接名不能重命名
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            int row = m_contextMenuTableRow;
            if (row < 0) {
                auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
                if (sel.isEmpty()) return;
                row = sel.first().row();
            }
            QString profileName;
            if (!m_contextMenuProfileName.isEmpty()) {
                profileName = m_contextMenuProfileName;
            } else if (tableWidgetNetwork->columnCount() > 3 && tableWidgetNetwork->item(row, 3)) {
                profileName = tableWidgetNetwork->item(row, 3)->text();
            } else {
                profileName = tableWidgetNetwork->item(row, 0)->text(); // 兜底
            }
            connName = profileName;
            if (connName.isEmpty()) return;
        }
        // 用完后清空
        m_contextMenuListItem = nullptr;
        m_contextMenuTableRow = -1;
        m_contextMenuProfileName.clear();
        bool ok = false;
        QString newName = QInputDialog::getText(this, "重命名连接", "新名称：", QLineEdit::Normal, connName, &ok);
        if (!ok || newName.isEmpty() || newName == connName) return;
        QString err;
        if (m_networkControl->renameConnection(connName, newName, &err)) {
            QTimer::singleShot(500, m_networkInfo, &NetworkInfo::refreshAll);
        } else {
            QMessageBox::critical(this, "重命名失败", err);
        }
    }

    void MainWindow::onStatusNetwork() {
        showNetworkStatusDialog();
    }

    void MainWindow::onSettingNetwork() {
        // 仅支持单选
        QString devName, connName;
        if (ui->listWidgetNetwork->isVisible()) {
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            if (selected.isEmpty()) return;
            QListWidgetItem* item = selected.first();
            devName = item->data(Qt::UserRole).toString();
            connName = item->data(Qt::UserRole+1).toString();
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            if (sel.isEmpty()) return;
            int row = sel.first().row();
            devName = tableWidgetNetwork->item(row, 2) ? tableWidgetNetwork->item(row, 2)->text() : "";
            connName = tableWidgetNetwork->item(row, 0) ? tableWidgetNetwork->item(row, 0)->text() : "";
        }
        if (devName.isEmpty()) return;
        
        // 检查是否为bond-slave-*连接
        bool isBondSlave = false;
        for (const auto &conn : m_connections) {
            if (conn.device == devName && conn.name == connName) {
                if (conn.name.startsWith("bond-slave-")) {
                    isBondSlave = true;
                }
                break;
            }
        }
        
        if (isBondSlave) {
            QMessageBox::information(this, "从属网卡", 
                QString("这是从属网卡 %1，其配置由主接口管理。\n\n如需修改网络配置，请修改主接口（bond0）的配置。").arg(connName));
            return;
        }
        
        ConnectionInfo connInfo;
        DeviceInfo devInfo;
        for (const auto &conn : m_connections) {
            // 优先匹配device和name都匹配的情况
            if (conn.device == devName && conn.name == connName) { 
                connInfo = conn; 
                break; 
            }
            // 如果device为空，只匹配name
            if (conn.device.isEmpty() && conn.name == connName) { 
                connInfo = conn; 
                break; 
            }
            // 如果name为空，只匹配device
            if (conn.name.isEmpty() && conn.device == devName) { 
                connInfo = conn; 
                break; 
            }
        }
        if (m_networkInfo) {
            for (const auto &dev : m_networkInfo->getAllDevices()) {
                if (dev.name == devName) { devInfo = dev; break; }
            }
        }
        NetworkPropertyDialog *dlg = new NetworkPropertyDialog(connInfo, devInfo, this);
        dlg->exec();
        delete dlg;
    }

    void MainWindow::onRefreshView() {
        fprintf(stderr, "刷新视图\n");
    }

    void MainWindow::updateStatusBar(int selectedCount) {
        int totalItems = 0;
        if (ui->listWidgetNetwork->isVisible()) {
            totalItems = ui->listWidgetNetwork->count();
            if (selectedCount == -1)
                selectedCount = ui->listWidgetNetwork->selectedItems().count();
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            totalItems = tableWidgetNetwork->rowCount();
            if (selectedCount == -1 && tableWidgetNetwork->selectionModel())
                selectedCount = tableWidgetNetwork->selectionModel()->selectedRows().count();
        }
        statusMessageWidget->setText(QString("共%1个项目  选中%2个").arg(totalItems).arg(selectedCount));
    }

    MainWindow::~MainWindow()
    {
        delete ui;
    }

    void MainWindow::loadNetworkConnections()
    {
        // 获取真实的网络连接数据
        m_connections = m_networkInfo->getAllConnections();
        updateNetworkList();
    }

    void MainWindow::updateNetworkList()
    {
        // 1. 记录当前选择状态
        QSet<QString> selectedDevs;
        for (QListWidgetItem *item : ui->listWidgetNetwork->selectedItems()) {
            selectedDevs.insert(item->data(Qt::UserRole).toString());
        }
        
        // 2. 获取最新数据
        QList<DeviceInfo> devices = m_networkInfo->getAllDevices();
        QList<ConnectionInfo> connections = m_networkInfo->getAllConnections();
        
        // 3. 现有项目map
        QMap<QString, QListWidgetItem*> deviceItemMap;
            for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
                QListWidgetItem *item = ui->listWidgetNetwork->item(i);
            if (item) {
                deviceItemMap.insert(item->data(Qt::UserRole).toString(), item);
            }
        }
        
        // 4. 遍历新数据，更新或创建
            for (const auto &dev : devices) {
                if (dev.type == DeviceType::Loopback) continue;

                // 收集所有与当前设备相关的profile（device字段或name字段匹配）
                QList<ConnectionInfo> profiles;
                for (const auto &conn : connections) {
                    if (conn.device == dev.name || conn.name == dev.name) profiles << conn;
                }
                // 优先选中已激活的profile，否则取第一个
                ConnectionInfo activeProfile;
                for (const auto &conn : profiles) {
                    if (conn.status == ConnectionStatus::Connected) { activeProfile = conn; break; }
                }
                if (activeProfile.name.isEmpty() && !profiles.isEmpty()) {
                    activeProfile = profiles.first();
                }

                QString iconPath, name, desc, statusText;
                QString typeText;
                switch (dev.type) {
                    case DeviceType::Ethernet: typeText = "以太网"; break;
                    case DeviceType::WiFi: typeText = "WLAN"; break;
                    default: typeText = "未知"; break;
                }
                QString firstLine = QString("%1(%2)").arg(typeText, dev.name);

                    if (!activeProfile.name.isEmpty()) {
                    // 图标根据设备启用状态和连接状态双重判断
                    ConnectionStatus statusToShow = activeProfile.status;
                    if (statusToShow == ConnectionStatus::Unknown) statusToShow = ConnectionStatus::Disconnected;
                    if (!dev.isEnabled) statusToShow = ConnectionStatus::Disconnected;
                    iconPath = m_networkInfo->getDeviceIconPath(dev.type, statusToShow);
                        name = firstLine;
                        desc = activeProfile.name;
                        switch (activeProfile.status) {
                    case ConnectionStatus::Connected: statusText = "已连接"; break;
                    case ConnectionStatus::Disconnected: statusText = dev.isEnabled ? "已断开" : "未启用"; break;
                    case ConnectionStatus::Connecting: statusText = "连接中"; break;
                    case ConnectionStatus::Disconnecting: statusText = "断开中"; break;
                        default: statusText = dev.isEnabled ? "未连接" : "未启用"; break;
                    }
            } else if (!profiles.isEmpty()) {
                        const ConnectionInfo &conn = profiles.first();
                    iconPath = m_networkInfo->getDeviceIconPath(dev.type, dev.isEnabled ? ConnectionStatus::Disconnected : ConnectionStatus::Disconnected);
                        name = firstLine;
                        desc = conn.name;
                        statusText = dev.isEnabled ? "未连接" : "未启用";
                } else {
                    iconPath = m_networkInfo->getDeviceIconPath(dev.type, dev.isEnabled ? ConnectionStatus::Disconnected : ConnectionStatus::Disconnected);
                    name = firstLine;
                    desc = "未配置网络连接";
                    statusText = "未连接";
                }

            QListWidgetItem* item = deviceItemMap.value(dev.name, nullptr);
            if (item) {
                // 已存在，更新
                NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
                if (cardWidget) {
                    cardWidget->updateData(QPixmap(iconPath), name, desc, statusText);
                }
                item->setData(Qt::UserRole+1, !activeProfile.name.isEmpty() ? activeProfile.name : (profiles.isEmpty() ? "" : profiles.first().name));
                deviceItemMap.remove(dev.name);
            } else {
                // 不存在，创建
                NetworkCardWidget *cardWidget = new NetworkCardWidget(QPixmap(iconPath), name, desc, statusText);
                QListWidgetItem *newItem = new QListWidgetItem();
                ui->listWidgetNetwork->addItem(newItem);
                ui->listWidgetNetwork->setItemWidget(newItem, cardWidget);
                cardWidget->setViewMode(m_currentViewMode);
                cardWidget->updateGeometry();
                newItem->setSizeHint(cardWidget->sizeHint());
                newItem->setData(Qt::UserRole, dev.name);
                newItem->setData(Qt::UserRole+1, !activeProfile.name.isEmpty() ? activeProfile.name : (profiles.isEmpty() ? "" : profiles.first().name));
            }
        }

        // 5. 移除已不存在的旧项目
        for (QListWidgetItem* itemToRemove : deviceItemMap.values()) {
            delete ui->listWidgetNetwork->takeItem(ui->listWidgetNetwork->row(itemToRemove));
        }

        // 6. 恢复选择状态
        ui->listWidgetNetwork->blockSignals(true);
        for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
            QListWidgetItem *item = ui->listWidgetNetwork->item(i);
            item->setSelected(selectedDevs.contains(item->data(Qt::UserRole).toString()));
        }
        ui->listWidgetNetwork->blockSignals(false);

        // 触发一次选中变化处理和状态栏更新
        onNetworkSelectionChanged();

        // --- 修复：每次刷新后强制所有卡片重新应用当前视图模式和sizeHint，防止间距变大 ---
        for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
            QListWidgetItem *item = ui->listWidgetNetwork->item(i);
            NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
            if (cardWidget) {
                cardWidget->setViewMode(m_currentViewMode);
                cardWidget->updateGeometry();
                item->setSizeHint(cardWidget->sizeHint());
            }
        }
    }

    void MainWindow::updateTableView() {
        if (!tableWidgetNetwork || !tableWidgetNetwork->isVisible()) return;
        // 记录当前选中设备名
        QString selectedDev;
        auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
        if (!sel.isEmpty()) {
            int row = sel.first().row();
            selectedDev = tableWidgetNetwork->item(row, 2) ? tableWidgetNetwork->item(row, 2)->text() : "";
        }
        tableWidgetNetwork->setRowCount(0);
        for (int i = 0; i < ui->listWidgetNetwork->count(); ++i) {
            QListWidgetItem *item = ui->listWidgetNetwork->item(i);
            NetworkCardWidget *cardWidget = qobject_cast<NetworkCardWidget*>(ui->listWidgetNetwork->itemWidget(item));
            if (cardWidget) {
                int row = tableWidgetNetwork->rowCount();
                tableWidgetNetwork->insertRow(row);
                QString statusText = cardWidget->findChild<QLabel*>("statusLabel") ? cardWidget->findChild<QLabel*>("statusLabel")->text() : "";
                QString nameText = cardWidget->findChild<QLabel*>("nameLabel") ? cardWidget->findChild<QLabel*>("nameLabel")->text() : "";
                QString descText = cardWidget->findChild<QLabel*>("descLabel") ? cardWidget->findChild<QLabel*>("descLabel")->text() : "";
                QTableWidgetItem *nameItem = new QTableWidgetItem();
                QString iconPath;
                if (statusText.contains("已连接")) {
                    iconPath = nameText.contains("WLAN") ? ":/icons/resources/small_wifi_connected.png" : ":/icons/resources/small_connected.png";
                } else {
                    iconPath = nameText.contains("WLAN") ? ":/icons/resources/small_wifi_disconnected.png" : ":/icons/resources/small_disconnected.png";
                }
                nameItem->setIcon(QIcon(iconPath));
                nameItem->setText(nameText);
                tableWidgetNetwork->setItem(row, 0, nameItem);
                tableWidgetNetwork->setItem(row, 1, new QTableWidgetItem(statusText));
                tableWidgetNetwork->setItem(row, 2, new QTableWidgetItem(descText));
                tableWidgetNetwork->setItem(row, 3, new QTableWidgetItem(descText));
                tableWidgetNetwork->setItem(row, 4, new QTableWidgetItem(statusText.contains("已连接") ? "Internet 访问" : "无访问"));
                tableWidgetNetwork->setItem(row, 5, new QTableWidgetItem("专用网络"));
                nameItem->setData(Qt::UserRole, item->data(Qt::UserRole));
                nameItem->setData(Qt::UserRole + 1, item->data(Qt::UserRole + 1));
                // 恢复选中
                if (!selectedDev.isEmpty() && descText == selectedDev) {
                    tableWidgetNetwork->selectRow(row);
                }
            }
        }
    }

    void MainWindow::onNetworkInfoUpdated() {
        m_connections = m_networkInfo->getAllConnections();
        updateNetworkList();
        if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            updateTableView();
        }
    }

    void MainWindow::onNetworkError(const QString &error)
    {
        // 可以在这里显示错误消息给用户
    }

    void MainWindow::onAddConnection() {
        QString devName;
        DeviceType devType = DeviceType::Unknown;
        if (ui->listWidgetNetwork->isVisible()) {
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            QListWidgetItem* item = selected.isEmpty() ? nullptr : selected.first();
            if (!item) return;
            devName = item->data(Qt::UserRole).toString();
            // 查找设备类型
            for (const auto &dev : m_networkInfo->getAllDevices()) {
                if (dev.name == devName) { devType = dev.type; break; }
            }
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            if (sel.isEmpty()) return;
            devName = tableWidgetNetwork->item(sel.first().row(), 2)->text();
            // 查找设备类型
            for (const auto &dev : m_networkInfo->getAllDevices()) {
                if (dev.name == devName) { devType = dev.type; break; }
            }
        }
        if (devName.isEmpty()) return;
        QString err;
        if (m_networkControl->addConnection(devName, devType, &err)) {
            QMessageBox::information(this, "新建连接", QString("已为设备 %1 创建自动获取IP的以太网连接！").arg(devName));
            m_networkInfo->refreshAll();
        } else {
            QMessageBox::critical(this, "新建连接失败", err);
        }
    }

    void MainWindow::showNetworkStatusDialog() {
        // 移除所有调试输出
        ConnectionInfo connInfo;
        DeviceInfo devInfo;
        QString devName;
        if (ui->listWidgetNetwork->isVisible()) {
            QList<QListWidgetItem*> selected = ui->listWidgetNetwork->selectedItems();
            if (selected.isEmpty()) return;
            QListWidgetItem* item = selected.first();
            devName = item->data(Qt::UserRole).toString();
        } else if (tableWidgetNetwork && tableWidgetNetwork->isVisible()) {
            auto sel = tableWidgetNetwork->selectionModel()->selectedRows();
            if (sel.isEmpty()) return;
                int row = sel.first().row();
            devName = tableWidgetNetwork->item(row, 2) ? tableWidgetNetwork->item(row, 2)->text() : "";
        }
        if (devName.isEmpty()) return;
        
        // 检查是否为bond-slave-*连接，如果是则显示提示信息
        bool isBondSlave = false;
        QString connName;
        for (const auto &conn : m_networkInfo->getAllConnections()) {
            if (conn.device == devName) { 
                connInfo = conn; 
                connName = conn.name;
                if (conn.name.startsWith("bond-slave-")) {
                    isBondSlave = true;
                }
                break; 
            }
        }
        
        if (isBondSlave) {
            QMessageBox::information(this, "从属网卡", 
                QString("这是从属网卡 %1，其配置由主接口管理。\n\n如需查看网络状态，请查看主接口（bond0）的状态信息。").arg(connName));
            return;
        }
        
        if (m_networkInfo) {
                for (const auto &dev : m_networkInfo->getAllDevices()) {
                if (dev.name == devName) { devInfo = dev; break; }
                }
        }
            NetworkStatusDialog dlg(connInfo, devInfo, m_networkInfo, this);
        dlg.setStats(m_networkInfo->getDeviceStats(devName));
            dlg.exec();
    }
    
// 绑定功能实现
void MainWindow::onBondNetworks(const QList<ConnectionInfo>& selectedConns)
{
    // 创建绑定配置对话框
    BondConfigDialog dlg(selectedConns, this);
    if (dlg.exec() != QDialog::Accepted) {
        return;
    }
    
    QString bondName = dlg.getBondName();
    QString bondMode = dlg.getBondMode();
    int miiInterval = dlg.getMiiMonitorInterval();
    int upDelay = dlg.getUpDelay();
    int downDelay = dlg.getDownDelay();
    QList<QString> devices = dlg.getSelectedDevices();
    
    QString errorMsg;
    
    // 创建绑定接口
    if (!createBondInterface(bondName, bondMode, miiInterval, upDelay, downDelay, devices, errorMsg)) {
        QMessageBox::critical(this, "绑定失败", "创建绑定接口失败:\n" + errorMsg);
        return;
    }
    
    // 配置从属网卡
    if (!configureBondSlaves(bondName, devices, errorMsg)) {
        QMessageBox::critical(this, "绑定失败", "配置从属网卡失败:\n" + errorMsg);
        return;
    }
    
    QMessageBox::information(this, "绑定成功", 
                           QString("网卡绑定成功!\n绑定接口: %1\n模式: %2\n从属网卡: %3")
                           .arg(bondName)
                           .arg(bondMode)
                           .arg(devices.join(", ")));
    
    // 刷新网络信息
    refreshNetworkInfo();
}

bool MainWindow::createBondInterface(const QString& bondName, const QString& bondMode, 
                                   int miiInterval, int upDelay, int downDelay, 
                                   const QList<QString>& devices, QString& errorMsg)
{
    QProcess process;
    
    // 1. 创建绑定接口 (使用nmcli，不需要root权限)
    process.start("nmcli", QStringList() << "connection" << "add" << "type" << "bond" 
                                        << "con-name" << bondName << "ifname" << bondName 
                                        << "mode" << bondMode);
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "创建绑定接口失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    
    // 2. 设置MII监控间隔 (如果需要)
    if (miiInterval > 0) {
        process.start("nmcli", QStringList() << "connection" << "modify" << bondName 
                                            << "bond.options" << QString("miimon=%1").arg(miiInterval));
        process.waitForFinished(3000);
    }
    
    // 3. 设置启动延迟 (如果需要)
    if (upDelay > 0) {
        process.start("nmcli", QStringList() << "connection" << "modify" << bondName 
                                            << "bond.options" << QString("updelay=%1").arg(upDelay));
        process.waitForFinished(3000);
    }
    
    // 4. 设置关闭延迟 (如果需要)
    if (downDelay > 0) {
        process.start("nmcli", QStringList() << "connection" << "modify" << bondName 
                                            << "bond.options" << QString("downdelay=%1").arg(downDelay));
        process.waitForFinished(3000);
    }
    
    return true;
}

bool MainWindow::configureBondSlaves(const QString& bondName, const QList<QString>& devices, QString& errorMsg)
{
    QProcess process;
    // 1. 获取当前bond的所有slave连接
    QList<QString> oldSlaves;
    process.start("nmcli", QStringList() << "connection" << "show");
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "获取连接列表失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    QString output = QString::fromUtf8(process.readAllStandardOutput());
    for (const QString& line : output.split('\n')) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.startsWith("bond-slave-")) {
            QStringList parts = trimmedLine.split(QRegularExpression("\\s+"));
            if (parts.size() >= 4) {
                QString slaveName = parts[0];
                QString slaveDev = parts[3];
                // 检查master是否为bondName
                QProcess detailProc;
                detailProc.start("nmcli", QStringList() << "connection" << "show" << slaveName);
                detailProc.waitForFinished(2000);
                QString detailOut = QString::fromUtf8(detailProc.readAllStandardOutput());
                if (detailOut.contains(QString("master: %1").arg(bondName))) {
                    oldSlaves << slaveDev;
                }
            }
        }
    }
    // 2. 先删除未勾选成员的 slave profile
    QProcess listProc;
    listProc.start("nmcli", QStringList() << "connection" << "show");
    listProc.waitForFinished(5000);
    QString outputList = QString::fromUtf8(listProc.readAllStandardOutput());
    QStringList allLines = outputList.split('\n');
    for (const QString& line : allLines) {
        QString trimmed = line.trimmed();
        if (trimmed.startsWith("bond-slave-")) {
            QStringList parts = trimmed.split(QRegularExpression("\\s+"));
            if (parts.size() >= 4) {
                QString slaveName = parts[0];
                QString slaveDev = parts[3];
                if (!devices.contains(slaveDev)) {
                    int delTries = 0;
                    while (delTries < 3) {
                        QProcess delProc;
                        delProc.start("nmcli", QStringList() << "connection" << "delete" << slaveName);
                        delProc.waitForFinished(2000);
                        QProcess checkProc;
                        checkProc.start("nmcli", QStringList() << "connection" << "show" << slaveName);
                        checkProc.waitForFinished(2000);
                        if (checkProc.exitCode() != 0) break;
                        ++delTries;
                    }
                    // 恢复物理网卡
                    QProcess reconnectProc;
                    reconnectProc.start("nmcli", QStringList() << "device" << "connect" << slaveDev);
                    reconnectProc.waitForFinished(3000);
                }
            }
        }
    }
    // 3. 再为新勾选且不存在的成员添加 slave profile
    for (const QString& device : devices) {
        QString slaveName = QString("bond-slave-%1").arg(device);
        QProcess checkProc;
        checkProc.start("nmcli", QStringList() << "connection" << "show" << slaveName);
        checkProc.waitForFinished(2000);
        if (checkProc.exitCode() == 0) {
            // 已存在，跳过添加
            continue;
        }
        // 添加
        process.start("nmcli", QStringList() << "connection" << "add" << "type" << "ethernet"
                                            << "slave-type" << "bond" << "con-name" << slaveName
                                            << "ifname" << device << "master" << bondName);
        bool addOk = process.waitForFinished(5000) && process.exitCode() == 0;
        if (!addOk) {
            errorMsg = QString("添加从属网卡 %1 失败: %2")
                      .arg(device)
                      .arg(QString::fromUtf8(process.readAllStandardError()));
            return false;
        }
    }
    // 4. 启用绑定接口
    process.start("nmcli", QStringList() << "connection" << "down" << bondName);
    process.waitForFinished(3000);
    process.start("nmcli", QStringList() << "connection" << "up" << bondName);
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "启用绑定接口失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    // 5. 启用所有从属网卡
    for (const QString& device : devices) {
        QString slaveName = QString("bond-slave-%1").arg(device);
        process.start("nmcli", QStringList() << "connection" << "down" << slaveName);
        process.waitForFinished(2000);
        process.start("nmcli", QStringList() << "connection" << "up" << slaveName);
        process.waitForFinished(3000);
    }
    return true;
}

void MainWindow::refreshNetworkInfo()
{
    if (m_networkInfo) {
        m_networkInfo->refreshAll();
    }
}

// 解绑功能实现
void MainWindow::onUnbondNetwork(const ConnectionInfo& bondConn)
{
    // 确认对话框
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认解除绑定", 
        QString("确定要解除绑定接口 %1 吗？\n\n"
                "解除绑定后：\n"
                "• 绑定接口将被删除\n"
                "• 从属网卡将恢复为独立网卡\n"
                "• 网络连接可能会暂时中断\n\n"
                "是否继续？").arg(bondConn.name),
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply != QMessageBox::Yes) {
        return;
    }
    
    QString errorMsg;
    
    // 执行解绑操作
    if (!unbondInterface(bondConn.name, errorMsg)) {
        QMessageBox::critical(this, "解除绑定失败", "解除绑定失败:\n" + errorMsg);
        return;
    }
    
    QMessageBox::information(this, "解除绑定成功", 
                           QString("绑定接口 %1 已成功解除绑定！\n\n"
                                  "从属网卡已恢复为独立网卡。").arg(bondConn.name));
    
    // 刷新网络信息
    refreshNetworkInfo();
}

bool MainWindow::unbondInterface(const QString& bondName, QString& errorMsg)
{
    QProcess process;
    
    // 1. 获取从属网卡列表（通过查找bond-slave-*连接）
    QList<QString> slaveDevices;
    process.start("nmcli", QStringList() << "connection" << "show");
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "获取连接列表失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    
    QString output = QString::fromUtf8(process.readAllStandardOutput());
    for (const QString& line : output.split('\n')) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.startsWith("bond-slave-")) {
            // 解析bond-slave-ens37  36a14bf7-793e-41ca-a52e-4c927e5d6d9a  ethernet  ens37
            QStringList parts = trimmedLine.split(QRegularExpression("\\s+"));
            if (parts.size() >= 4) {
                QString slaveConnName = parts[0];
                QString slaveDevice = parts[3];
                // 检查这个从属网卡是否属于当前bond
                process.start("nmcli", QStringList() << "connection" << "show" << slaveConnName);
                if (process.waitForFinished(3000) && process.exitCode() == 0) {
                    QString slaveOutput = QString::fromUtf8(process.readAllStandardOutput());
                    for (const QString& slaveLine : slaveOutput.split('\n')) {
                        if (slaveLine.trimmed().startsWith("connection.master:") && 
                            slaveLine.section(':', 1).trimmed() == bondName) {
                            slaveDevices.append(slaveDevice);
                            break;
                        }
                    }
                }
            }
        }
    }
    
    if (slaveDevices.isEmpty()) {
        errorMsg = "未找到从属网卡";
        return false;
    }
    
    // 2. 禁用绑定接口
    process.start("nmcli", QStringList() << "connection" << "down" << bondName);
    process.waitForFinished(3000);
    
    // 3. 删除从属网卡连接
    for (const QString& slaveDevice : slaveDevices) {
        QString slaveConnName = QString("bond-slave-%1").arg(slaveDevice);
        process.start("nmcli", QStringList() << "connection" << "delete" << slaveConnName);
        process.waitForFinished(3000);
    }
    
    // 4. 删除绑定接口连接
    process.start("nmcli", QStringList() << "connection" << "delete" << bondName);
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "删除绑定接口连接失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    
    // 5. 删除绑定设备
    process.start("nmcli", QStringList() << "device" << "delete" << bondName);
    process.waitForFinished(3000);
    
    // 6. 恢复物理网卡连接（如果存在原始连接）
    for (const QString& slaveDevice : slaveDevices) {
        // 尝试激活原始连接（如果存在）
        process.start("nmcli", QStringList() << "device" << "connect" << slaveDevice);
        process.waitForFinished(3000);
    }
    
    return true;
    }
    
// 桥接功能实现
void MainWindow::onBridgeNetworks(const QList<ConnectionInfo>& selectedConns)
{
    // 创建桥接配置对话框
    BridgeConfigDialog dlg(selectedConns, this);
    // 自动勾选主界面选中的网卡
    QStringList initialDevices;
    for (const ConnectionInfo& conn : selectedConns) initialDevices << conn.device;
    dlg.setSelectedDevices(initialDevices);
    if (dlg.exec() != QDialog::Accepted) {
        return;
    }
    QString bridgeName = dlg.getBridgeName();
    bool stpEnabled = dlg.getStpEnabled();
    int stpPriority = dlg.getStpPriority();
    int forwardDelay = dlg.getForwardDelay();
    int helloTime = dlg.getHelloTime();
    int maxAge = dlg.getMaxAge();
    QStringList selectedDevices = dlg.getSelectedDevices();
    QString errorMsg;
    // 创建桥接接口
    if (!createBridgeInterface(bridgeName, stpEnabled, stpPriority, forwardDelay, helloTime, maxAge, selectedDevices, errorMsg)) {
        QMessageBox::critical(this, "桥接失败", "创建桥接接口失败:\n" + errorMsg);
        return;
    }
    // 配置从属网卡
    if (!configureBridgeSlaves(bridgeName, selectedDevices, errorMsg)) {
        QMessageBox::critical(this, "桥接失败", "配置从属网卡失败:\n" + errorMsg);
        return;
    }
    QMessageBox::information(this, "桥接成功", 
                           QString("网卡桥接成功!\n桥接接口: %1\n从属网卡: %2")
                           .arg(bridgeName)
                           .arg(selectedDevices.join(", ")));
    // 刷新网络信息
    refreshNetworkInfo();
}

bool MainWindow::createBridgeInterface(const QString& bridgeName, bool stpEnabled, int stpPriority,
                                     int forwardDelay, int helloTime, int maxAge,
                                     const QList<QString>& devices, QString& errorMsg)
{
    QProcess process;
    
    // 1. 创建桥接接口
    process.start("nmcli", QStringList() << "connection" << "add" << "type" << "bridge" 
                                        << "con-name" << bridgeName << "ifname" << bridgeName);
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "创建桥接接口失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    
    // 2. 配置STP参数
    if (stpEnabled) {
        process.start("nmcli", QStringList() << "connection" << "modify" << bridgeName 
                                            << "bridge.stp" << "yes");
        process.waitForFinished(3000);
        
        process.start("nmcli", QStringList() << "connection" << "modify" << bridgeName 
                                            << "bridge.priority" << QString::number(stpPriority));
        process.waitForFinished(3000);
        
        process.start("nmcli", QStringList() << "connection" << "modify" << bridgeName 
                                            << "bridge.forward-delay" << QString::number(forwardDelay));
        process.waitForFinished(3000);
        
        process.start("nmcli", QStringList() << "connection" << "modify" << bridgeName 
                                            << "bridge.hello-time" << QString::number(helloTime));
        process.waitForFinished(3000);
        
        process.start("nmcli", QStringList() << "connection" << "modify" << bridgeName 
                                            << "bridge.max-age" << QString::number(maxAge));
        process.waitForFinished(3000);
    } else {
        process.start("nmcli", QStringList() << "connection" << "modify" << bridgeName 
                                            << "bridge.stp" << "no");
        process.waitForFinished(3000);
    }
    
    return true;
}

bool MainWindow::configureBridgeSlaves(const QString& bridgeName, const QList<QString>& devices, QString& errorMsg)
{
    QProcess process;
    // 1. 获取当前bridge的所有slave连接
    QList<QString> oldSlaves;
    process.start("nmcli", QStringList() << "connection" << "show");
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "获取连接列表失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    QString output = QString::fromUtf8(process.readAllStandardOutput());
    for (const QString& line : output.split('\n')) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.startsWith("bridge-slave-")) {
            QStringList parts = trimmedLine.split(QRegularExpression("\\s+"));
            if (parts.size() >= 4) {
                QString slaveName = parts[0];
                QString slaveDev = parts[3];
                // 检查master是否为bridgeName
                QProcess detailProc;
                detailProc.start("nmcli", QStringList() << "connection" << "show" << slaveName);
                detailProc.waitForFinished(2000);
                QString detailOut = QString::fromUtf8(detailProc.readAllStandardOutput());
                if (detailOut.contains(QString("master: %1").arg(bridgeName))) {
                    oldSlaves << slaveDev;
                }
            }
        }
    }
    // 2. 添加成功后，删除未勾选成员的 slave profile
    QProcess listProc;
    listProc.start("nmcli", QStringList() << "connection" << "show");
    listProc.waitForFinished(5000);
    QString outputList = QString::fromUtf8(listProc.readAllStandardOutput());
    QStringList allLines = outputList.split('\n');
    for (const QString& line : allLines) {
        QString trimmed = line.trimmed();
        if (trimmed.startsWith("bridge-slave-")) {
            QStringList parts = trimmed.split(QRegularExpression("\\s+"));
            if (parts.size() >= 4) {
                QString slaveName = parts[0];
                QString slaveDev = parts[3];
                if (!devices.contains(slaveDev)) {
                    int delTries = 0;
                    while (delTries < 3) {
                        QProcess delProc;
                        delProc.start("nmcli", QStringList() << "connection" << "delete" << slaveName);
                        delProc.waitForFinished(2000);
                        QProcess checkProc;
                        checkProc.start("nmcli", QStringList() << "connection" << "show" << slaveName);
                        checkProc.waitForFinished(2000);
                        if (checkProc.exitCode() != 0) break;
                        ++delTries;
                    }
                    // 恢复物理网卡
                    QProcess reconnectProc;
                    reconnectProc.start("nmcli", QStringList() << "device" << "connect" << slaveDev);
                    reconnectProc.waitForFinished(3000);
                }
            }
        }
    }
    // 3. 先尝试为新slave添加连接（不删旧的）
    QList<QString> addedSlaves;
    for (const QString& device : devices) {
        QString slaveName = QString("bridge-slave-%1").arg(device);
        QProcess checkProc;
        checkProc.start("nmcli", QStringList() << "connection" << "show" << slaveName);
        checkProc.waitForFinished(2000);
        if (checkProc.exitCode() == 0) {
            // 已存在，跳过添加
            continue;
        }
        // 添加
        process.start("nmcli", QStringList() << "connection" << "add" << "type" << "ethernet"
                                            << "slave-type" << "bridge" << "con-name" << slaveName
                                            << "ifname" << device << "master" << bridgeName);
        bool addOk = process.waitForFinished(5000) && process.exitCode() == 0;
        if (!addOk) {
            errorMsg = QString("添加从属网卡 %1 失败: %2")
                      .arg(device)
                      .arg(QString::fromUtf8(process.readAllStandardError()));
            return false;
        }
    }
 
    // 4. 启用桥接接口
    process.start("nmcli", QStringList() << "connection" << "down" << bridgeName);
    process.waitForFinished(3000);
    process.start("nmcli", QStringList() << "connection" << "up" << bridgeName);
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "启用桥接接口失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    // 5. 启用所有从属网卡
    for (const QString& device : devices) {
        QString slaveName = QString("bridge-slave-%1").arg(device);
        process.start("nmcli", QStringList() << "connection" << "down" << slaveName);
        process.waitForFinished(2000);
        process.start("nmcli", QStringList() << "connection" << "up" << slaveName);
        process.waitForFinished(3000);
    }
    return true;
}

void MainWindow::onUnbridgeNetwork(const ConnectionInfo& bridgeConn)
{
    // 检查是否是桥接接口
    if (!bridgeConn.name.startsWith("br")) {
        QMessageBox::warning(this, "操作错误", "选择的不是桥接接口");
        return;
    }
    
    // 确认对话框
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认解除桥接",
        QString("确定要解除桥接接口 %1 吗？\n\n"
                "解除桥接后：\n"
                "• 桥接接口将被删除\n"
                "• 从属网卡将恢复为独立网卡\n"
                "• 网络连接可能会暂时中断\n\n"
                "是否继续？").arg(bridgeConn.name),
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply != QMessageBox::Yes) {
        return;
    }
    
    QString errorMsg;
    
    // 执行解桥接操作
    if (!unbridgeInterface(bridgeConn.name, errorMsg)) {
        QMessageBox::critical(this, "解除桥接失败", "解除桥接失败:\n" + errorMsg);
        return;
    }
    
    QMessageBox::information(this, "解除桥接成功", 
                           QString("桥接接口 %1 已成功解除桥接！\n\n"
                                  "从属网卡已恢复为独立网卡。").arg(bridgeConn.name));
    
    // 刷新网络信息
    refreshNetworkInfo();
}

bool MainWindow::unbridgeInterface(const QString& bridgeName, QString& errorMsg)
{
    QProcess process;
    
    // 1. 获取从属网卡列表（通过查找bridge-slave-*连接）
    QList<QString> slaveDevices;
    process.start("nmcli", QStringList() << "connection" << "show");
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "获取连接列表失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    
    QString output = QString::fromUtf8(process.readAllStandardOutput());
    for (const QString& line : output.split('\n')) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.startsWith("bridge-slave-")) {
            // 解析bridge-slave-ens37  36a14bf7-793e-41ca-a52e-4c927e5d6d9a  ethernet  ens37
            QStringList parts = trimmedLine.split(QRegularExpression("\\s+"));
            if (parts.size() >= 4) {
                QString slaveConnName = parts[0];
                QString slaveDevice = parts[3];
                // 检查这个从属网卡是否属于当前bridge
                process.start("nmcli", QStringList() << "connection" << "show" << slaveConnName);
                if (process.waitForFinished(3000) && process.exitCode() == 0) {
                    QString slaveOutput = QString::fromUtf8(process.readAllStandardOutput());
                    for (const QString& slaveLine : slaveOutput.split('\n')) {
                        if (slaveLine.trimmed().startsWith("connection.master:") && 
                            slaveLine.section(':', 1).trimmed() == bridgeName) {
                            slaveDevices.append(slaveDevice);
                            break;
                        }
                    }
                }
            }
        }
    }
    
    if (slaveDevices.isEmpty()) {
        errorMsg = "未找到从属网卡";
        return false;
    }
    
    // 2. 禁用桥接接口
    process.start("nmcli", QStringList() << "connection" << "down" << bridgeName);
    process.waitForFinished(3000);
    
    // 3. 删除从属网卡连接
    for (const QString& slaveDevice : slaveDevices) {
        QString slaveConnName = QString("bridge-slave-%1").arg(slaveDevice);
        process.start("nmcli", QStringList() << "connection" << "delete" << slaveConnName);
        process.waitForFinished(3000);
    }
    
    // 4. 删除桥接接口连接
    process.start("nmcli", QStringList() << "connection" << "delete" << bridgeName);
    if (!process.waitForFinished(5000) || process.exitCode() != 0) {
        errorMsg = "删除桥接接口连接失败: " + QString::fromUtf8(process.readAllStandardError());
        return false;
    }
    
    // 5. 删除桥接设备
    process.start("nmcli", QStringList() << "device" << "delete" << bridgeName);
    process.waitForFinished(3000);
    
    // 6. 恢复物理网卡连接（如果存在原始连接）
    for (const QString& slaveDevice : slaveDevices) {
        // 尝试激活原始连接（如果存在）
        process.start("nmcli", QStringList() << "device" << "connect" << slaveDevice);
        process.waitForFinished(3000);
    }
    
    return true;
}
    
void MainWindow::onEditBondMembers(const ConnectionInfo& bondConn)
{
    // 获取所有物理网卡
    QList<DeviceInfo> allDevices = m_networkInfo->getAllDevices();
    QList<QString> currentSlaves;
    // 获取当前bond的所有slave
    for (const ConnectionInfo& conn : m_connections) {
        if (conn.name.startsWith("bond-slave-") && conn.device != bondConn.device && conn.status != ConnectionStatus::Unknown) {
            if (conn.device != bondConn.device && conn.status != ConnectionStatus::Unknown && conn.status != ConnectionStatus::Disconnected) {
                currentSlaves << conn.device;
            }
        }
    }
    // 允许所有未被占用的物理网卡+当前成员
    QList<ConnectionInfo> candidates;
    for (const DeviceInfo& dev : allDevices) {
        if (dev.type == DeviceType::Ethernet) {
            bool isSlave = false;
            for (const ConnectionInfo& conn : m_connections) {
                if ((conn.name.startsWith("bond-slave-") || conn.name.startsWith("bridge-slave-")) && conn.device == dev.name) {
                    // 只要不是当前bond的成员就算被占用
                    if (!currentSlaves.contains(dev.name)) {
                        isSlave = true;
                        break;
                    }
                }
            }
            if (!isSlave || currentSlaves.contains(dev.name)) {
                // 查找ConnectionInfo
                for (const ConnectionInfo& conn : m_connections) {
                    if (conn.device == dev.name) {
                        ConnectionInfo fullConn = conn;
                        // 补全 ipAddress 和 netmask
                        if (fullConn.ipAddress.isEmpty()) fullConn.ipAddress = dev.ipAddress;
                        if (fullConn.netmask.isEmpty()) fullConn.netmask = dev.netmask;
                        candidates << fullConn;
                        break;
                    }
                }
                // 如果没有找到对应的ConnectionInfo，创建一个基本的
                if (candidates.isEmpty() || candidates.last().device != dev.name) {
                    ConnectionInfo basicConn;
                    basicConn.device = dev.name;
                    basicConn.name = dev.name;
                    basicConn.type = dev.type;
                    basicConn.status = dev.state == "connected" ? ConnectionStatus::Connected : ConnectionStatus::Disconnected;
                    basicConn.macAddress = dev.macAddress;
                    basicConn.ipAddress = dev.ipAddress;
                    basicConn.netmask = dev.netmask;
                    candidates << basicConn;
                }
            }
        }
    }
    BondConfigDialog dlg(candidates, bondConn.device, currentSlaves, this);
    if (dlg.exec() != QDialog::Accepted) return;
    QList<QString> selectedDevices = dlg.getSelectedDevices();
    QString errorMsg;
    if (!configureBondSlaves(bondConn.device, selectedDevices, errorMsg)) {
        QMessageBox::critical(this, "编辑绑定成员失败", errorMsg);
        return;
    }
    refreshNetworkInfo();
}

void MainWindow::onEditBridgeMembers(const ConnectionInfo& bridgeConn)
{
    QList<DeviceInfo> allDevices = m_networkInfo->getAllDevices();
    QStringList currentSlaves;
    for (const ConnectionInfo& conn : m_connections) {
        if (conn.name.startsWith("bridge-slave-") && conn.device != bridgeConn.device && conn.status != ConnectionStatus::Unknown) {
            if (conn.device != bridgeConn.device && conn.status != ConnectionStatus::Unknown && conn.status != ConnectionStatus::Disconnected) {
                currentSlaves << conn.device;
            }
        }
    }
    // 修正：允许所有未被占用的物理网卡+当前成员
    QList<ConnectionInfo> candidates;
    for (const DeviceInfo& dev : allDevices) {
        if (dev.type == DeviceType::Ethernet) {
            bool isSlave = false;
            for (const ConnectionInfo& conn : m_connections) {
                if ((conn.name.startsWith("bond-slave-") || conn.name.startsWith("bridge-slave-")) && conn.device == dev.name) {
                    // 只要不是当前桥的成员就算被占用
                    if (!currentSlaves.contains(dev.name)) {
                    isSlave = true;
                    break;
                    }
                }
            }
            if (!isSlave || currentSlaves.contains(dev.name)) {
                // 查找ConnectionInfo
                for (const ConnectionInfo& conn : m_connections) {
                    if (conn.device == dev.name) {
                        ConnectionInfo fullConn = conn;
                        // 补全 ipAddress 和 netmask
                        if (fullConn.ipAddress.isEmpty()) fullConn.ipAddress = dev.ipAddress;
                        if (fullConn.netmask.isEmpty()) fullConn.netmask = dev.netmask;
                        candidates << fullConn;
                        break;
                    }
                }
            }
        }
    }
    // 获取br0的IP和掩码
    QString brIp, brMask;
    for (const ConnectionInfo& conn : m_connections) {
        if (conn.device == bridgeConn.device && !conn.ipAddress.isEmpty() && !conn.netmask.isEmpty()) {
            brIp = conn.ipAddress;
            brMask = conn.netmask;
            break;
        }
    }
    BridgeConfigDialog dlg(candidates, this, brIp, brMask);
    dlg.setWindowTitle("编辑桥接成员");
    dlg.setBridgeName(bridgeConn.device);
    dlg.setSelectedDevices(currentSlaves);
    if (dlg.exec() != QDialog::Accepted) return;
    QStringList selectedDevices = dlg.getSelectedDevices();
    // 如果没有任何变更，直接返回，不做任何操作
    QStringList sortedOld = currentSlaves, sortedNew = selectedDevices;
    std::sort(sortedOld.begin(), sortedOld.end());
    std::sort(sortedNew.begin(), sortedNew.end());
    if (sortedOld == sortedNew) return;
    fprintf(stderr, "[BridgeDebug] 编辑桥接成员最终选择: ");
    for (const auto& s : selectedDevices) fprintf(stderr, "%s ", s.toUtf8().constData());
    fprintf(stderr, "\n");
    QString errorMsg;
    if (!configureBridgeSlaves(bridgeConn.device, selectedDevices, errorMsg)) {
        QMessageBox::critical(this, "编辑桥接成员失败", errorMsg);
        return;
    }
    refreshNetworkInfo();
    }

    void MainWindow::showAboutDialog() {
        AboutDialog dlg(this);
        dlg.exec();
    }
    